const BASEURL = getApp().globalData.BASEURL
let is401Handled = false // 标记401是否已处理，防止重复弹窗

const request = (config) => {
	let header = {
		"Content-Type": config.contentType || "application/json;charset=utf-8",
	}
	let data = {
		...config.data,
		timestamp: Math.floor(Date.now() / 1000),
		sign: 'sign'
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + config.url,
			data: data || '',
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('userToken'),
				'token': uni.getStorageSync('userToken'),
				'type': '3',
			},
			method: config.method,
			dataType: "json",
			success: (res) => {
				const {
					data
				} = res
				const {
					code
				} = data

				switch (code) {
					case 200:
						resolve(res.data)
						break
					case 401:
						// 处理401错误（登录过期）
						if (!is401Handled) {
							uni.showToast({
								title:'登录已过期',
								icon:"none"
							})
							is401Handled = true // 标记为已处理，防止重复弹窗
							uni.clearStorageSync() // 清除过期的登录信息
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index',
									complete: () => {
										is401Handled = false // 跳转完成后重置标记
									}
								})
							}, 1000)

							// // 显示提示弹窗
							// uni.showModal({
							//   title: '提示',
							//   content: '登录状态已过期，请重新登录',
							//   cancelText: '取消',
							//   confirmText: '确定',
							//   showCancel: false, // 强制用户只能点击确定
							//   success: function() {
							//     // 跳转到首页
							//     uni.reLaunch({
							//       url: '/pages/index/index',
							//       complete: () => {
							//         is401Handled = false // 跳转完成后重置标记
							//       }
							//     })
							//   }
							// })
						}
						return // 终止当前Promise流程，不执行后续逻辑
					case 99990001:
					case 99990002:
						resolve(res.data)
						break
					default:
						resolve(res.data)
						uni.showToast({
							title: data.msg || '操作失败',
							duration: 2000,
							mask: false,
							icon: "none"
						})
				}
			},
			fail: (error) => {
				uni.showToast({
					title: "请求错误",
					duration: 1500,
					mask: false,
					icon: "none"
				});
				reject(error)
			},
			complete: () => {
				// 可添加请求完成后的通用逻辑
			}
		})
	})
}

export default request